package com.cm.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cm.admin.entity.Admin;
import com.cm.admin.entity.dto.AdminKeyWordDTO;
import com.cm.admin.mapper.AdminMapper;
import com.cm.admin.service.AdminService;
import com.cm.common.core.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @类 名:AdminController </br>
 * @描 述:<br>
 * @日 期:2020/9/22 17:28 </br>
 * @作 者:小兰同学</br>
 * @版 本：1.0.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private AdminService adminService;
    @PostMapping("/insert")
    public Result insert(@RequestBody Admin admin) {
        if (adminService.insert(admin)) {
            return Result.success("用户添加成功");
        }
        return Result.fail(admin.getUsername() + "已存在！");
    }
    @PostMapping("/delete")
    public Result delete(Long id) {
        if (adminService.delete(id)) {
            return Result.success("删除成功");
        }
        return Result.fail("删除失败");
    }

    @PostMapping("/update")
    public Result update(@RequestBody Admin admin) {
        if (adminService.update(admin)) {
            return Result.success("修改成功");
        }
        return Result.fail("修改失败");
    }

    @PostMapping("/list")
    public Result getUsers(@RequestBody AdminKeyWordDTO adminKeyWordDTO) {
        IPage<Admin> userIPage = adminService.getAdminList(adminKeyWordDTO);
        return Result.success(userIPage);
    }
    @GetMapping("/getById")
    public Result getById(Long id){
        Admin admin=adminMapper.selectById(id);
        return Result.success(admin);
    }
    @GetMapping("/getByName")
    public Result getByName(String username){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("username",username);
        Admin admin=adminMapper.selectOne(queryWrapper);
        return Result.success(admin);
    }
    @PostMapping("/updateByName")
    public Result updateByName(@RequestBody Admin admin){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("username",admin.getUsername());
        int i=adminMapper.update(admin,queryWrapper);
        if (i>0){
            return Result.success("更新成功");
        }
        return Result.fail("更新失败");
    }
}
